﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SettingsXmlSerializer.cs" company="DevDigital">
//   DevDigital
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Settings.NET.Serializers
{
    using System;
    using System.IO;
    using System.Xml.Serialization;

    /// <summary>
    /// Settings - XML serializer
    /// Provides XML serialization/deserialization
    /// </summary>
    [Serializable]
    public class SettingsXmlSerializer : ISettingsSerializer
    {
        /// <summary>
        /// Serializes the specified value.
        /// </summary>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="value">The value.</param>
        /// <returns>The serialized value</returns>
        public string Serialize<TValue>(TValue value)
        {
            try
            {
                using (var writer = new StringWriter())
                {
                    var xmlSerializer = new XmlSerializer(typeof(TValue));
                    xmlSerializer.Serialize(writer, value);
                    return writer.ToString();
                }
            }
            catch
            {
                return null;
            }         
        }

        /// <summary>
        /// Deserializes the specified value.
        /// </summary>
        /// <typeparam name="TValue">The type of the value.</typeparam>
        /// <param name="value">The value.</param>
        /// <returns>The deserialized value</returns>
        public TValue Deserialize<TValue>(string value)
        {
            try
            {
                using (TextReader reader = new StringReader(value))
                {
                    var xmlSerializer = new XmlSerializer(typeof(TValue));
                    var deserialised = xmlSerializer.Deserialize(reader);
                    var returnValue = deserialised is TValue ? (TValue)deserialised : default(TValue);
                    return returnValue;
                }
            }
            catch
            {
                return default(TValue);
            }           
        }        
    }
}